<template>
  <div>
    <!-- 一级弹框 -->
    <el-dialog
      title="价格组参照关系设置"
      :visible.sync="showPriceGroupVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      width="65%"
      @close="handleCloseShowDialog"
    >
      <el-row class="heigher_table_wrap">
        <el-button
          type="primary"
          @click="handleChooseSetGroup"
          :loading="setPriceGroupBtnLoading"
          >价格组设置</el-button
        >
      </el-row>
      <el-table
        :data="showPriceGroupTableData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        border="border"
        use-virtual
        height="400px"
      >
        <el-table-column
          v-for="column in columns"
          :key="column.key"
          :prop="column.key"
          :label="column.title"
          :property="column.key"
          :align="column.align"
          :min-width="column.width || 120"
          :fixed="column.fixed"
          :formatter="column.formatter"
          :show-overflow-tooltip="true"
        >
          <template v-if="column.type === 'inputNumber'" v-slot="scope">
            <el-input-number
              v-model="scope.row[scope.column.property]"
              placeholder="请输入..."
              :disabled="scope.row.isDisabled"
              :precision="2"
              :controls="false"
            ></el-input-number>
          </template>
          <template v-else-if="column.type === 'select'" v-slot="scope">
            <el-select
              v-model="scope.row[scope.column.property]"
              placeholder="请选择"
              @change="
                (val) => {
                  handleChooseReferenceGroup({
                    val,
                    row: scope.row,
                    index: scope.$index,
                  });
                }
              "
            >
              <el-option
                v-for="item in referenceGroupList"
                :key="item.uuid"
                :label="item.groupName"
                :value="item.uuid"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseShowDialog">返回</el-button>
        <el-button type="primary" @click="handleSubmitPriceGroup" :loading="submitBtnLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <!-- 二级弹框 -->
    <el-dialog
      width="65%"
      :visible="setPriceGroupVisible"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="handleCloseSetDialog"
      title="价格组设置"
    >
      <el-row class="heigher_table_wrap">
        <el-button
          type="primary"
          :disabled="setPriceGroupTableData.length === 0"
          @click="handleToGroupByProvince"
          >各省成组</el-button
        >
      </el-row>
      <el-table
        v-loading="setGroupTableLoading"
        :data="setPriceGroupTableData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        border="border"
        use-virtual
        height="400px"
      >
        <el-table-column
          v-for="item in setPriceGroupTableColumns"
          :key="item.key"
          :prop="item.key"
          :label="item.title"
          :property="item.key"
          :align="item.align"
          :min-width="item.width || 120"
          :fixed="item.fixed"
          :formatter="item.formatter"
          :show-overflow-tooltip="true"
        >
          <template v-if="item.type === 'input'" v-slot="scope">
            <el-input
              v-model="scope.row.groupNum"
              placeholder="请输入..."
            ></el-input>
          </template>
          <template v-else-if="item.type === 'radio'" v-slot="scope">
            <el-radio-group
              v-model="scope.row.mainCity"
              @change="
                (val) => {
                  handleChangeIsMainCity({
                    val,
                    row: scope.row,
                    index: scope.$index,
                  });
                }
              "
            >
              <el-radio label="1" :disabled="scope.row.canSetMain == 2"
                >是</el-radio
              >
              <el-radio label="2" :disabled="scope.row.canSetMain == 2"
                >否</el-radio
              >
            </el-radio-group>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseSetDialog">取 消</el-button>
        <el-button
          type="primary"
          @click="handleMakeSure"
          :disabled="setPriceGroupTableData.length === 0"
        >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { generateUuid } from '@/utils/bizUtils';
import { getCityNamesByPriceIneligibleRatio } from '@/utils/getUtils';
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      default () {
        return [
          {
            title: '组名称',
            key: 'groupName',
            align: 'center'
          },
          {
            title: '主城市',
            key: 'mainCity',
            align: 'center'
          },
          {
            title: '参照组',
            key: 'mainGroupUuid',
            align: 'center',
            type: 'select'
          },
          {
            title: '价格比例',
            key: 'rate',
            align: 'center',
            type: 'inputNumber'
          }
        ];
      }
    },
    getReferenceGroupUrl: {
      type: String,
      default: '/sysback/salepriceskubatchadd/getByOper'
    },
    productUuids: {
      type: Array,
      default () {
        return [];
      }
    },
    apiRequestUrl: {
      type: String,
      default: '/sysback/salepricesku/initAreaList?authCreateGroupNum=1'
    },
    submitUrl: {
      type: String,
      default: '/sysback/salepricesku/createGroupAndAreaRel'
    },
    isQueryPriceGroup: {
      type: Boolean,
      default: true
    },
    isAutoCloseDialog: { // 是否自动关闭弹框（在提交后）
      type: Boolean,
      default: true
    },
    submitBtnLoading: { // 一级弹框提交按钮loading
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      referenceGroupList: [],
      showPriceGroupTableData: [],
      showPriceGroupVisible: this.visible,
      setPriceGroupVisible: false,
      setPriceGroupBtnLoading: false,
      setGroupTableLoading: false,
      setPriceGroupTableData: [],
      setPriceGroupTableColumns: [
        {
          title: '设置组',
          key: 'groupNum',
          align: 'center',
          type: 'input'
        },
        {
          title: '组名',
          key: 'groupName'
        },
        {
          title: '省',
          key: 'provinceName'
        },
        {
          title: '主城市',
          key: 'cityName'
        },
        {
          title: '业务区域',
          key: 'areaName'
        },
        {
          title: '是否主省',
          slot: 'mainCity',
          align: 'center',
          type: 'radio'
        }
      ],
      batchSetGroupList: [],
      submitUuid: '', // 提交所需uuid（前端生成）
    };
  },
  watch: {
    /* 监听展示参照城市弹框开关 */
    visible (newValue) {
      this.showPriceGroupVisible = newValue;
      if (newValue && this.isQueryPriceGroup) {
        this.getReferenceGroupsAction();
      }
      if (!this.isQueryPriceGroup) {
        this.showPriceGroupTableData = [];
      }
    }
  },
  methods: {
    /* --------- 一级弹框-价格组设置方式 --------- */
    /**
     * 获取一级弹框-价格组设置方式的表格数据
     * @mainGroupuuid 参照组下拉框的城市id
     * @rate 价格比例，默认为1
     * @isDisabled 价格比例输入框的禁用状态，价格组城市参照自己的时候禁用输入框
     */
    getReferenceGroupsAction () {
      let data = {
        productUuid: this.productUuids.join(',')
      };
      ApiRequest(`${this.getReferenceGroupUrl}?uuid=${this.submitUuid}`, 'post', data, true).then((res) => {
        if (res.retStatus !== '1' || !res.retData) {
          return false;
        }
        // 增加输入框禁用属性并判断
        this.showPriceGroupTableData = res.retData.map((item) => {
          let obj = { ...item, isDisabled: false };
          if (!obj.mainGroupUuid) {
            obj.mainGroupUuid = obj.uuid;
          }
          if (obj.mainGroupUuid === obj.uuid) {
            obj.isDisabled = true;
            obj.rate = 1;
          }
          return obj;
        });
        this.referenceGroupList =
          res.retData &&
          res.retData.map((item) => ({
            uuid: item.uuid,
            groupName: item.groupName
          }));
      });
    },
    /* 点击参照组下拉框进行城市选择所触发的事件 */
    handleChooseReferenceGroup (data) {
      let { val, row, index } = data;
      this.showPriceGroupTableData[index].mainGroupUuid = val;
      // 判断当前数据中的uuid是否等于选中数据的uuid
      if (row.uuid === val) {
        // 自己参照自己
        this.showPriceGroupTableData[index].rate = 1;
        this.showPriceGroupTableData[index].isDisabled = true;
      } else {
        this.showPriceGroupTableData[index].rate = 1;
        this.showPriceGroupTableData[index].isDisabled = false;
      }
    },
    /* 关闭价格组设置方式弹框的方法 */
    handleCloseShowDialog () {
      this.showPriceGroupVisible = false;
      this.$emit('update:visible', this.showPriceGroupVisible);
    },
    /* 提交价格组设置方式弹框的表格数据 */
    handleSubmitPriceGroup () {
      const warnMsgs = getCityNamesByPriceIneligibleRatio(this.showPriceGroupTableData);
      if (warnMsgs) {
        return this.$message.warning(`${warnMsgs}：价格比例需在0.6-5之间`);
      }
      this.$emit('getSetGroupList', {
        tableData: this.showPriceGroupTableData,
        uuid: this.submitUuid // 传出提交uuid
      });
      if (this.isAutoCloseDialog) {
        this.handleCloseShowDialog();
      }
    },
    /* --------- 二级弹框-价格组设置 --------- */
    /* 点击选择组设置方式按钮的事件，打开二级弹框 */
    handleChooseSetGroup () {
      this.setPriceGroupVisible = true;
      this.getPriceGroupListAction();
    },
    /* 获取所有价格组数据列表的方法 */
    getPriceGroupListAction () {
      let data = {
        productUuids: this.productUuids,
        areaType: 1
      };
      if (!this.productUuids) {
        return this.$message.warning('没有productUuid,请确认');
      }
      this.setGroupTableLoading = true;
      ApiRequest(this.apiRequestUrl, 'post', data, false).then((res) => {
        this.setGroupTableLoading = false;
        if (res.retStatus !== '1') {
          return false;
        }
        res.retData.forEach((item) => {
          item.oldMainCityName = item.cityName;
          item.oldMainCityCode = item.cityCode;
        });
        this.setPriceGroupTableData = res.retData.map((item) => ({
          ...item,
          productUuid: this.productUuids.join(',')
        }));
        this.batchSetGroupList = res.retData.reduce((value, item) => {
          if (item.canSetMain === '1') {
            value.push({
              groupNum: item.cityCode,
              groupName: item.cityName
            });
          }
          return value;
        }, []);
      });
    },
    /* 关闭二级弹框的事件方法 */
    handleCloseSetDialog () {
      this.setPriceGroupVisible = false;
    },
    /* 二级弹框的提交事件方法 */
    handleMakeSure () {
      this.setGroupTableLoading = true;
      this.submitUuid = generateUuid(); // 每次二级弹框提交时重新生成
      ApiRequest(`${this.submitUrl}?uuid=${this.submitUuid}`, 'post', this.setPriceGroupTableData, false)
        .then((res) => {
          this.setGroupTableLoading = false;
          if (res.retStatus !== '1') {
            return false;
          }
          this.getReferenceGroupsAction(); // 获取一级弹框-价格组设置方式的表格数据
          this.handleCloseSetDialog(); // 关闭二级弹框
        })
        .catch(() => {
          this.setGroupTableLoading = false;
        });
    },
    /* 是否主省radio的change事件方法 */
    handleChangeIsMainCity (data) {
      let { val, row, index } = data;
      this.setPriceGroupTableData[index].mainCity = val; // 单选赋值
      /* 同一 设置组 只能选一个主城市 */
      if (val === '2') {
        return false;
      }
      this.setPriceGroupTableData.forEach((value, i) => {
        if (value.groupNum === row.groupNum) {
          value.groupName = row.oldMainCityName;
          if (i !== index) {
            this.setPriceGroupTableData[i].mainCity = '2';
          }
        }
      });
    },
    // 各省成组
    handleToGroupByProvince () {
      this.setPriceGroupTableData = _.cloneDeep(this.setPriceGroupTableData).reduce((value, item, index) => {
        if (item.canSetMain === '1') {
          item.groupNum = (index + 1).toString();
          item.mainCity = '1';
        }
        value.push(item);
        return value;
      }, []);
      this.setPriceGroupTableData.filter(
        item => item.mainCity === '1' && item.canSetMain === '1'
      ).forEach((item, index) => {
        this.handleChangeIsMainCity({ val: item.mainCity, row: item, index });
      });
    }
  }
};
</script>
<style lang="less" scoped>
.dialog-footer {
  text-align: center;
}

.heigher_table_wrap {
  margin-bottom: 15px;
}

/deep/ .el-dialog__header {
  border-bottom: 1px solid #ebebeb;
}

/deep/ .el-dialog__body {
  padding: 15px 20px;
}
</style>
